package com.acmen.easyapi.repository;

import com.acmen.easyapi.dbcp.JdbcService;
import com.acmen.easyapi.model.Api;
import com.acmen.easyapi.util.StringUtil;
import com.acmen.easyapi.util.UUID;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

;

/**
 * @author acmen
 */
@Component
public class ApiRepository {

    private final static String QUERY_BY_ID_SQL = "select * from t_api where id=?";
    private final static String QUERY_LIST_BY_IDS_SQL = "select * from t_api where id in";
    private final static String QUERY_BY_APP_SQL = "select * from t_api where app_name=?  order by module, idx,no,name";
    private final static String INSERT_API_DETAIL_SQL = "insert into t_api" +
            "(id,idx,app_name,module,name,no,request_method,path,author,creator,note,completed,req_param_node,res_param_node,rpc,permission,md5) " +
            "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    private final static String UPDATE_API_DETAIL_RPC_SQL = "update t_api set rpc=? where id=?";
    private final static String INSERT_API_VERSION_SQL = "insert into t_api_version (id,app_name,api_id,api_name,md5) values(?,?,?,?,?)";
    private final static String DELETE_SQL = "delete from t_api where id=?";
    private final static String DELETE_API_VERSION_SQL = "delete from t_api_version where api_id=?";
    private final static String CHECK_VERSION_SQL = "select 1 from t_api_version where api_id=? and md5=?";

    @Resource
    private JdbcService jdbcService;

    /**
     * 根据ID查询出记录
     *
     * @param appName
     * @return
     */
    public List<Api> selectListByAppName(String appName) {
        return jdbcService.selectList(QUERY_BY_APP_SQL, new Object[]{appName},Api.class);
    }

    public Api selectById(String id) {
        return jdbcService.selectOne(QUERY_BY_ID_SQL, new Object[]{id},Api.class);
    }

    public List<Api> selectListByIds(List<String> ids) {
        return jdbcService.selectList(QUERY_LIST_BY_IDS_SQL + StringUtil.getInPlaceholder(ids.size()), ids.toArray(),Api.class);
    }



    public int[] batchCreate(List<Api> apis) {
        List<Object[]> insertApiBatchArgs = new ArrayList<>();
        List<Object[]> versionBatchArgs = new ArrayList<>();
        for(Api api : apis){
            Object[] args = {api.getId(),api.getIdx(), api.getAppName(),api.getModule(),api.getName(),api.getNo(),
                    api.getRequestMethod(), api.getPath(),api.getAuthor(),api.getCreator(), api.getNote(),api.isCompleted(),
                    toJSONString(api.getReqParamNode()),toJSONString(api.getResParamNode())
                    ,toJSONString(api.getRpc()),api.getPermission(),api.getMd5()};
            insertApiBatchArgs.add(args);
            versionBatchArgs.add(new Object[]{UUID.genUUID32(),api.getAppName(),api.getId(),api.getName(),api.getMd5()});
        }
        jdbcService.batchUpdate(INSERT_API_VERSION_SQL,versionBatchArgs);
        return jdbcService.batchUpdate(INSERT_API_DETAIL_SQL,insertApiBatchArgs);
    }


    public int[] batchDelete(List<String> apiIds) {
        List<Object[]> deleteApiBatchArgs = apiIds.stream().map(apiId->new Object[]{apiId}).collect(Collectors.toList());
       return jdbcService.batchUpdate(DELETE_SQL,deleteApiBatchArgs);
    }


    public void batchDeleteWithVersion(List<String> apiIds){
        apiIds.forEach(apiId->{
            jdbcService.update(DELETE_SQL,new Object[]{apiId});
            jdbcService.update(DELETE_API_VERSION_SQL,new Object[]{apiId});
        });
    }

    public boolean exits(String apiId,String md5){
        return jdbcService.selectOne(CHECK_VERSION_SQL,new Object[]{apiId,md5})!=null;
    }


    public String toJSONString(Object obj){
        if(StringUtil.isEmpty(obj)){
            return null;
        }
        return JSON.toJSONString(obj);
    }
}
